<?php

class Core_Table_Foundation_Catalogue extends Kd_Data_Table {

    private $_relationTable = '{t}foundation_catalogue_relation';

    public function __construct() {
        parent::__construct();
    }

    public function getRelations(array $codes) {
        return Kd_Data_Factory::getQueryDcl()
                ->from($this->_relationTable)
                ->where()->contain('catalogue_code', ':codes:s')->closest()
                ->addParameter('codes', $codes)
                ->setDbDriver($this->getDbDriver())
                ->fetch();
    }

    public function insertRelation($catalogueCode, array $parents, $transaction = NULL) {
        $insert = Kd_Data_Factory::getInsertDcl()
                        ->into($this->_relationTable)
                        ->value('catalogue_code', "'$catalogueCode'")
                        ->value('parent_code', ':parentCode:s')
                        ->value('code_path', ':codePath:s')
                        ->toSql();
        $driver = $this->getDbDriver($transaction);
        foreach ($parents as $parent) {
            $driver->setSql($insert, $parent)->execute();
        }
    }

    public function deleteRelation($catalogueCode, $transaction = NULL) {
        Kd_Data_Factory::getDeleteDcl()
                ->from($this->_relationTable)
                ->where()->eq('catalogue_code', "'$catalogueCode'")->closest()
                ->setDbDriver($this->getDbDriver($transaction))
                ->execute();
    }

}